import numpy as np
import os
from PIL import Image
import tensorflow as tf

# 训练集和测试集的路径，需修改
orl_train_dir = 'C:/Users/lakuite/Desktop/orl2/train'
orl_test_dir = 'C:/Users/lakuite/Desktop/orl2/test'
orl_train_list = os.listdir(orl_train_dir)
orl_test_list = os.listdir(orl_test_dir)
x = tf.placeholder("float", shape=[None, 56 * 46])
y_ = tf.placeholder("float", shape=[None, 40])

# 参数设置
lr = 0.001
epoch = 25
batch_size = 40
step = 9  # 360/40
n_class = 40  # 类别


# 读取训练数据
def orl_data(orl_train_list):
    # 1. 获取图片和标签数组
    train_data = []
    train_label = []
    for train_index, train_img in enumerate(orl_train_list):
        train_img_path = orl_train_dir + '/' + train_img

        # 图片数组
        image = Image.open(train_img_path)
        image_arr = np.array(image)

        # 图片类别
        _class = int(train_index / 9)

        # 把读入的图片加到数组里
        train_data.append(image_arr)
        train_label.append(_class)

    # 2. 制作one-hot标签
    train_label = tf.one_hot(train_label, n_class)

    # print(np.shape(train_data))
    # print(train_label)
    return train_data, train_label


# 读取测试数据
def test_data(orl_test_list):
    test_data = []
    test_label = np.arange(0, 40, 1)
    test_label = tf.one_hot(test_label, n_class)
    print(test_label)
    for test_index, test_img in enumerate(orl_test_list):
        test_img_path = orl_test_dir + '/' + test_img
        image = Image.open(test_img_path)
        image_arr = np.array(image)
        test_data.append(image_arr)
    return test_data, test_label


# 获得训练/测试批次
def get_Batch(data, label, batch_size):
    data = np.array(data)
    print(data.shape, label.shape)
    input_queue = tf.train.slice_input_producer([data, label], num_epochs=epoch, shuffle=True,
                                                capacity=32)  # test: False
    x_batch, y_batch = tf.train.batch(input_queue, batch_size=batch_size, num_threads=1, capacity=32,
                                      allow_smaller_final_batch=False)
    return x_batch, y_batch


# 定义权重
def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)


# 定义偏置
def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)


# 定义卷积
def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')


# 定义池化
def max_pool_2x2(x):
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                          strides=[1, 2, 2, 1], padding='SAME')


# 网络结构
# 1. 第一层卷积： 56x46x1 --> 28x23x32
x_image = tf.reshape(x, [-1, 56, 46, 1])
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
# 2. 第二层卷积： 28x23x32 --> 14x12x64
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
# 3. 全连接层： 14x12x64 --> 1024
W_fc1 = weight_variable([14 * 12 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 14 * 12 * 64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
# 4. dropout防过拟合
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
# 5. 输出层： 1024 --> 40类
W_fc2 = weight_variable([1024, n_class])
b_fc2 = bias_variable([n_class])
y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2

# 6. 评估和训练模型
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits
                               (labels=y_, logits=y_conv))
train_step = tf.train.AdamOptimizer(lr).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

saver = tf.train.Saver()

# 训练数据
data, label = orl_data(orl_train_list)
# data, label = test_data(orl_test_list)
x_batch, y_batch = get_Batch(data, label, batch_size)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    sess.run(tf.local_variables_initializer())

    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess, coord)

    # saver.restore(sess, "C:/Users/lakuite/Desktop/orl2/save_net.ckpt")

    i = 0  # epoch
    acc_list = []
    try:
        while not coord.should_stop():
            xs, ys = sess.run([x_batch, y_batch])
            xs = xs.reshape((batch_size, 56 * 46))
            _, train_accuracy, train_loss, tmp = sess.run([train_step, accuracy, cross_entropy, y_conv],
                                                          feed_dict={x: xs, y_: ys, keep_prob: 0.5})
            # test_accuracy, y_pre = sess.run([accuracy, tf.argmax(y_conv, 1)],
            #                               feed_dict={x: xs, y_: ys, keep_prob: 1.0})

            # print(tmp)
            save_path = saver.save(sess, "C:/Users/lakuite/Desktop/orl2/net/save_net0604.ckpt")
            # 打印结果，batch_size=40，360张图，故每个epoch有9个step
            if (i + 1) % step == 0:
                print("eopch %d: training accuracy %f, loss %f" % ((i + 1) / step, train_accuracy, train_loss))
            # print("pic %d: acc %f" % (i, test_accuracy))
            # 打印识别错误项的标签
            # if test_accuracy==0.0:
            #     print('label:', y_pre)
            # acc_list.append(test_accuracy)
            i = i + 1

    except tf.errors.OutOfRangeError:  # num_epochs 次数用完会抛出此异常
        print("---Train/Test end---")
        # print("test_acc: %f" % np.mean(acc_list))
    finally:
        # 协调器coord发出所有线程终止信号
        coord.request_stop()
        print('---Programm end---')
    coord.join(threads)